package com.probiz.estoresa.order.web.action;

import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.Constants;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.order.OrderDelivery;
import com.probiz.estore.common.model.order.OrderExpress;
import com.probiz.estore.common.model.order.OrderShipment;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.order.service.OrderDeliveryManager;
import com.probiz.estore.order.service.OrderExpressManager;
import com.probiz.estore.order.service.OrderShipmentManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class OrderShipController extends GenericStoreAdminController<OrderShipment> {
    private OrderShipmentManager orderShipmentManager ;
    private OrderExpressManager  orderExpressManager ;
    private OrderDeliveryManager orderDeliveryManager;

    public void setOrderShipmentManager(OrderShipmentManager inMgr) {
        this.orderShipmentManager = inMgr;
    }
    
	public void setOrderExpressManager(OrderExpressManager orderExpressManager) {
		this.orderExpressManager = orderExpressManager;
	}
	

	public void setOrderDeliveryManager(OrderDeliveryManager orderDeliveryManager) {
		this.orderDeliveryManager = orderDeliveryManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(OrderShipment entity) {
		return entity.getOrderShipmentName();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.BaseController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = orderShipmentManager;
	}
	
	@Override
	protected Map<String,String> getSortMap4Direction(){
		Map<String,String> sortMap = new HashMap<String,String>();
		sortMap.put("1", "documentNo asc");
		sortMap.put("2", "documentNo desc");
		sortMap.put("3", "salesOrder.orderNo asc");
		sortMap.put("4", "salesOrder.orderNo desc");
		sortMap.put("5", "shippingCost asc");
		sortMap.put("6", "shippingCost desc");
		sortMap.put("7", "convert_gbk(deliveryTypeDesc) asc");
		sortMap.put("8", "convert_gbk(deliveryTypeDesc) desc");
		sortMap.put("9", "createTime asc");
		sortMap.put("10", "createTime desc");
		sortMap.put("11", "trackingNo asc");
		sortMap.put("12", "trackingNo desc");
		return sortMap;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected void preSave(HttpServletRequest request, OrderShipment entity, BindException errors) {
	}

	public ModelAndView search(HttpServletRequest request, HttpServletResponse response) {
		SearchCriteria sc = createSearchCriteria(request, OrderShipment.FilterHqlName.SEARCH_4_SHIP);
		List results = searchByCriteria(sc);
		return getModelAndView(listView, listModelName, results);
	}

	/**
	 * 打印发货单
	 * 
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView printShipList(HttpServletRequest request, HttpServletResponse response) {
		List<OrderShipment> orderShipmentList = new ArrayList<OrderShipment>();
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			for (String id: ids) {
				OrderShipment op=orderShipmentManager.getById(Integer.valueOf(id));
				orderShipmentList.add(op);
			}
		}
		ModelAndView mv = new ModelAndView("order/print/orderShipPrintList");
		mv.addObject("orderShipmentList", orderShipmentList);
		return mv;
	}
	/**
	 * 保存物流单号
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView saveTrackingNo(HttpServletRequest request, HttpServletResponse response) {
		String[] trackingNos = request.getParameterValues("trackingNo");
		String[] orderShipmentIds = request.getParameterValues("orderShipmentId");
		if (trackingNos != null && trackingNos.length > 0) {
			for (int i=0; i<trackingNos.length; i++) {
				Integer orderShipmentId = Integer.valueOf(orderShipmentIds[i]);
				OrderShipment orderShipment =orderShipmentManager.getById(orderShipmentId);
				orderShipment.setTrackingNo(trackingNos[i]);
				orderShipmentManager.save(orderShipment);
			}
		}
		saveMessage(request, getMessage("orderShippment.saveTrackingNo.success"));
		return search(request,response);
	}
	
	/**
	 * 查询快递100
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView queryKuaidi100(HttpServletRequest request, HttpServletResponse response){
		String documentNo = request.getParameter("documentNo");
		Short flag = orderShipmentManager.queryKuaidi100(documentNo);
		OrderShipment orderShipment = orderShipmentManager.getByDocumentNo(documentNo);
		ModelAndView mv = new ModelAndView("/order/include/orderShipList4Kuaidi100Message");
		mv.addObject("orderShipment", orderShipment);
		mv.addObject("flag", flag);
		return mv;
	}
	
	/**
	 * 快递单打印
	 * @param request
	 * @param response
	 * @return
	 */
	public ModelAndView printOrderExpress(HttpServletRequest request, HttpServletResponse response) {
		List<OrderShipment> orderShipmentList = new ArrayList<OrderShipment>();
		String[] ids = request.getParameterValues("multiIds");
		if (ids != null && ids.length > 0) {
			for (String id: ids) {
				OrderShipment op=orderShipmentManager.getById(Integer.valueOf(id));
				orderShipmentList.add(op);
			}
		}
		
		ModelAndView mv = new ModelAndView("order/print/orderExpressPrint");
		OrderDelivery orderDelivery=null;
		if(orderShipmentList.size()>0){
			List<String> printDataList = new ArrayList<String>();
			//获得当前的发货单
			//OrderShipment orderShipment=orderShipmentList.get(0);
			//mv.addObject("orderShipment",orderShipment);
			
			//返回所有可用的快递单模板
			List<OrderExpress> orderExpressList= orderExpressManager.listAvailableOrderExpress();
			OrderExpress defaultOrderExpress=null;
			//返回所有可用的发货地址
			List<OrderDelivery> orderDeliveryList=orderDeliveryManager.listByProperty("status",Constants.STATUS_ACTIVE);
			
			if(orderExpressList.size()>0){
				//返回一个默认显示的快递单模板
				defaultOrderExpress=orderExpressList.get(0);
			} else {
				if(orderDeliveryList!=null&&orderDeliveryList.size()>0){
					mv.addObject("orderDeliveryList", orderDeliveryList);
				}	
				return mv;
			}
			
			
			
			for(OrderShipment _orderShipment : orderShipmentList){
				//返回一个发货地址信息，用于默认显示
				if(orderDeliveryList!=null&&orderDeliveryList.size()>0){
					orderDelivery=orderDeliveryList.get(0);
				}else{
					mv.addObject("orderExpressList", orderExpressList);
					return mv;
				}	
				//如果快递单模板对应的运输方式和本发货单种的运输方式相同，则设置为默认的快递单模板
				for (Iterator iterator = orderExpressList.iterator(); iterator .hasNext();) {
					OrderExpress tmp_OrderExpress=(OrderExpress)iterator.next();
					if(tmp_OrderExpress.getShippingMethodId() != null && tmp_OrderExpress.getShippingMethodId().equals(_orderShipment.getShippingMethodId())){
						defaultOrderExpress=tmp_OrderExpress;
						break;
					}
				}
				String orderExpressId=RequestUtil.getParameterNullSafe(request, "orderExpressId");
				if(StringUtils.isNotBlank(orderExpressId)){
					defaultOrderExpress=orderExpressManager.getById(Integer.valueOf((orderExpressId)));
				}
				String orderDeliveryId=RequestUtil.getParameterNullSafe(request, "orderDeliveryId");
				if(StringUtils.isNotBlank(orderDeliveryId)){
					orderDelivery=orderDeliveryManager.getById(new Integer(orderDeliveryId));
				}else{
					//返回默认的发货信息,如果没有，返回列表的第一条数据
					try{
						for (Iterator iterator = orderDeliveryList.iterator(); iterator .hasNext();) {
							OrderDelivery tmp_orderDelivery = (OrderDelivery) iterator.next();
							if(tmp_orderDelivery.getIsDefault().equals(new Short("1"))){
								orderDelivery=tmp_orderDelivery;
								break;
							}
						}
						
					}catch(Exception e) {
						e.printStackTrace();
					}
					
				}
				//获取xml格式的字符串
				Document doc = orderExpressManager.getXmlFormatData(_orderShipment, orderDelivery);
				
				//输出xml格式的字符串
				StringWriter sw = new StringWriter();
				XMLWriter xw = new XMLWriter(sw);
				OutputFormat opf = OutputFormat.createCompactFormat();
				opf.setEncoding("UTF-8");			  
				try {
					xw.write(doc.getRootElement().elements());
					xw.close();
					/*		  		System.out.println("\n====================================");
		  		System.out.println(sw.toString());
		  		System.out.println("\n====================================");	*/
					printDataList.add("<store_name>"+ConfigUtil.getInstance().getStoreTitle()+"</store_name>"+sw.toString());
					//mv.addObject("printData", "<data><store_name>"+ConfigUtil.getInstance().getStoreTitle()+"</store_name>"+sw.toString()+"</data>");
					sw.close();			   
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			
			
		  	mv.addObject("printDataList",printDataList);
		  	StringBuffer sb = new StringBuffer();
			sb.append("<data>");
			for(String item : printDataList){
				sb.append("<item>").append(item).append("</item>");
			}
			sb.append("</data>");
			mv.addObject("printDatas",sb.toString());
		  	mv.addObject("count",printDataList.size());
		  	mv.addObject("defaultOrderDelivery", orderDelivery);	  
			mv.addObject("defaultOrderExpress", defaultOrderExpress);
			mv.addObject("orderExpressList", orderExpressList);
			mv.addObject("orderDeliveryList", orderDeliveryList);
		}
		return mv;
	}	
}
